import { useState, useEffect } from 'react';
import styles from './cart.module.css';
import { useNavigate } from 'react-router-dom';
import { Stepper, Toast } from 'react-vant';
import { ShoppingCart } from '@react-vant/icons';

// 从本地存储获取购物车数据
const getCartFromLocalStorage = () => {
  const cartData = localStorage.getItem('cartData');
  return cartData ? JSON.parse(cartData) : [
    { id: 1, shopName: '天猫 耀迈旗舰店', name: 'Jetson AGX Orin 开发套件', price: 12899, originalPrice: 14999, image: 'https://picsum.photos/id/1/200/200', count: 1, selected: false },
    { id: 2, shopName: '天猫 机械工业出版社旗舰店', name: '官网正版机械工业出版社 Kamailio实战', price: 34.65, originalPrice: 45, image: 'https://picsum.photos/id/2/200/200', count: 1, selected: false },
    { id: 3, shopName: '天猫 小米官方旗舰店', name: '超级立减 REDMI K80智能学生游戏', price: 1850.98, originalPrice: 2499, image: 'https://picsum.photos/id/3/200/200', count: 1, selected: false },
    { id: 4, shopName: '淘宝 WITWATIA', name: '站地毯上10秒不动，闹钟才能停止', price: 108.02, originalPrice: 147.8, image: 'https://picsum.photos/id/4/200/200', count: 1, selected: false }
  ];
};

const Cart = () => {
  const [cartItems, setCartItems] = useState(getCartFromLocalStorage());
  const [selectAll, setSelectAll] = useState(false);
  const [isEditMode, setIsEditMode] = useState(false);
  const navigate = useNavigate();

  // 保存购物车数据到本地存储
  useEffect(() => {
    localStorage.setItem('cartData', JSON.stringify(cartItems));
  }, [cartItems]);

  // 切换商品选中状态
  const toggleSelect = (id) => {
    const newItems = cartItems.map(item => item.id === id ? { ...item, selected: !item.selected } : item);
    setCartItems(newItems);
    // 更新全选状态
    setSelectAll(newItems.every(item => item.selected) && newItems.length > 0);
  };

  // 全选/取消全选
  const handleSelectAll = () => {
    setSelectAll(!selectAll);
    setCartItems(cartItems.map(item => ({ ...item, selected: !selectAll })));
  };

  // 删除商品
  const deleteItem = (id) => {
    Toast.success('删除成功');
    setCartItems(cartItems.filter(item => item.id !== id));
  };

  // 批量删除选中商品
  const batchDelete = () => {
    const newItems = cartItems.filter(item => !item.selected);
    if (newItems.length === cartItems.length) {
      Toast.info('请选择要删除的商品');
      return;
    }
    setCartItems(newItems);
    setSelectAll(false);
    Toast.success(`删除了${cartItems.length - newItems.length}件商品`);
  };

  // 调整商品数量
  const handleCountChange = (id, count) => {
    if (count < 1) {
      Toast.info('商品数量不能为0');
      return;
    }
    setCartItems(cartItems.map(item => item.id === id ? { ...item, count } : item));
  };

  // 计算总价
  const calculateTotal = () => {
    return cartItems
      .filter(item => item.selected)
      .reduce((total, item) => total + item.price * item.count, 0)
      .toFixed(2);
  };

  // 计算选中商品数量
  const getSelectedCount = () => {
    return cartItems
      .filter(item => item.selected)
      .reduce((total, item) => total + item.count, 0);
  };

  return (
    <div className={styles.cartContainer}>
      {/* 购物车头部 */}
      <div className={styles.cartHeader}>
        <h1 className={styles.cartTitle}>购物车</h1>
        <div className={styles.searchBox}><input type="text" placeholder="搜索购物车商品" className={styles.searchInput} /></div>
        <button 
          className={styles.manageBtn}
          onClick={() => setIsEditMode(!isEditMode)}
        >
          {isEditMode ? '完成' : '管理'}
        </button>
      </div>

      {/* 空购物车状态 */}
      {cartItems.length === 0 ? (
        <div className={styles.emptyCart}>
          <ShoppingCart className={styles.emptyIcon} />
          <p className={styles.emptyText}>购物车是空的</p>
          <button 
            className={styles.goShoppingBtn}
            onClick={() => navigate('/')}
          >
            去逛逛
          </button>
        </div>
      ) : (
        // 商品列表
        <div className={styles.productList}>
          {cartItems.map(item => (
            <div key={item.id} className={styles.productItem}>
              <div className={styles.checkboxWrapper}>
                <input 
                  type="checkbox" 
                  className={styles.checkbox} 
                  checked={item.selected} 
                  onChange={() => toggleSelect(item.id)} 
                />
              </div>
              <img src={item.image} alt={item.name} className={styles.productImage} />
              <div className={styles.productInfo}>
                <div className={styles.productShop}>{item.shopName}</div>
                <div className={styles.productName}>{item.name}</div>
                <div className={styles.productPrice}>
                  ¥{item.price.toFixed(2)}
                  <span className={styles.originalPrice}>¥{item.originalPrice.toFixed(2)}</span>
                </div>
              </div>
              <div className={styles.productActions}>
                {isEditMode ? (
                  <button 
                    className={styles.deleteBtn}
                    onClick={() => deleteItem(item.id)}
                  >
                    删除
                  </button>
                ) : (
                  <Stepper 
                    value={item.count} 
                    min={1} 
                    max={99} 
                    onChange={(value) => handleCountChange(item.id, value)} 
                  />
                )}
              </div>
            </div>
          ))}
        </div>
      )}

      {/* 购物车底部 */}
      {cartItems.length > 0 && (
        <div className={styles.cartFooter}>
          <div className={styles.selectAll}>
            <input type="checkbox" checked={selectAll} onChange={handleSelectAll} />
            <span>全选</span>
          </div>
          {isEditMode ? (
            <button className={styles.batchDeleteBtn} onClick={batchDelete}>删除选中</button>
          ) : (
            <div className={styles.footerRight}>
              <div className={styles.totalPrice}>
                合计: <span>¥{calculateTotal()}</span>
              </div>
              <button 
                className={styles.checkoutBtn}
                disabled={getSelectedCount() === 0}
              >
                结算 ({getSelectedCount()})
              </button>
            </div>
          )}
        </div>
      )}
    </div>
  );
};

export default Cart;
